<template>
  <div class="app-container customer-div">
    <!--数据列表-->
    <el-menu :default-active="listQuery.tab" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="1">我负责的</el-menu-item>
      <el-menu-item index="2">共享（师徒）</el-menu-item>
      <el-menu-item index="3" v-if="departmentPL">部门（军团）</el-menu-item>
      <el-menu-item index="4" v-if="allCustomersPL">全部</el-menu-item>
    </el-menu>

    <div class="table-container">
      <vxe-grid ref='followListXGrid' v-bind="gridOptions" size="mini" :loading="listLoading">
        <template #form>
          <!--搜索-->
          <div>
            <div style="background: #f5f7fa;padding:15px 15px 0 15px;border:1px solid #EBEEF5;border-bottom:0.5px solid #EBEEF5;">
              <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
                <el-form-item label="客户名称：">
                  <el-select
                    clearable
                    v-model="listQuery.customerName"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词"
                    :remote-method="querySearch">
                    <el-option
                      v-for="item in querySearchList"
                      :key="item.customerId"
                      :label="item.customerName"
                      :value="item.customerName">
                    </el-option>
                  </el-select>
                </el-form-item>
<!--                <el-form-item label="联系人：">-->
<!--                   <el-input v-model="listQuery.contactName" clearable></el-input>-->
<!--                </el-form-item>-->
<!--                <el-form-item label="负责人：" v-if="listQuery.tab != '1'">-->
<!--                  <el-select v-model="listQuery.userId" filterable placeholder="请选择" clearable >-->
<!--                    <el-option-->
<!--                      v-for="item in userOptionList"-->
<!--                      :key="item.userId"-->
<!--                      :label="item.userName"-->
<!--                      :value="item.userId">-->
<!--                    </el-option>-->
<!--                  </el-select>-->
<!--                </el-form-item>-->
                <el-form-item label="跟进人：" v-if="listQuery.tab != '1'">
                  <el-select v-model="listQuery.trackingUserId" filterable placeholder="请选择" clearable >
                    <el-option
                      v-for="item in userOptionList"
                      :key="item.userId"
                      :label="item.userName"
                      :value="item.userId">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="跟进内容：">
                  <el-input v-model="listQuery.trackingContent"></el-input>
                </el-form-item>
                <el-form-item label="跟进方式：">
                  <el-select  v-model="listQuery.trackingTypeId" placeholder="请选择" clearable>
                    <el-option v-for="item in customerTrackingList"  :value="item.cddId" :label="item.cddValue" :key="item.cddId"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="创建时间：">
                  <el-date-picker
                    v-model="listQuery.date"
                    type="daterange"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="跟进类型：">
                  <el-select  v-model="listQuery.isInvalid" placeholder="请选择" clearable>
                    <el-option  :value="0" label="有效" :key="0"></el-option>
                    <el-option  :value="1" label="无效" :key="1"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="过滤成交条件：">
                  <el-select  v-model="listQuery.isDeal" placeholder="请选择" clearable>
                    <el-option  :value="0" label="不过滤" :key="0"></el-option>
                    <el-option  :value="1" label="过滤" :key="1"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button @click="handleSearchList" type="primary">查询</el-button>
                  <el-button @click="showGj" type="primary" v-if="listQuery.tab == 1">新增跟进</el-button>
                  <el-button type="primary" v-if="exportfollow"  @click="downloadExcel()" :loading="btnLoading">导出</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </template>
        <template #pager>
          <div style="overflow: hidden">
            <div class="pagination-container" style="float:right;">
              <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                layout="total, sizes,prev, pager, next,jumper"
                :current-page.sync="listQuery.pageNum"
                :page-size="listQuery.pageSize"
                :page-sizes="[10,15,20,50,100,200]"
                :total="count">
              </el-pagination>
            </div>
          </div>
        </template>
        <template #toolbar_buttons>
          <span style="padding-left:20px">跟进客户数合计{{ customerCount }}个，跟进记录{{count}}条</span>
        </template>
        <template #num1_default="{ row, rowIndex }">
          <el-link @click="toDetail(row)" type="primary"  style="font-size:12px;">{{row.customerName}}</el-link>
        </template>
        <template #num2_default="{ row, rowIndex }">
          {{row.isInvalid == 0 ? '有效' : '无效'}}
        </template>
      </vxe-grid>
    </div>
    <addGj ref="addGj" @getList="getList"></addGj>
  </div>
</template>
<script>
import store from '@/store'
import { mapGetters } from 'vuex'
import {customerPotential, getOrderUsersList,getCustomerOption,getCustomerSetting} from "@/api/partner";
import {customerNewTrackingList,customerNewDelTracking} from '@/api/company'
import addGj from './components/addGj'
const defaultListQuery={
"tab": '1' ,   //1:  我负责的  2 共享 3 部门 4 全部
"goodsLineId":'' ,    //产品线id筛选,
"customerName": '' ,   //客户名称,
"customerId": '',    //客户id,
"userId": '' ,   //负责人id,
"trackingUserId": '' ,  //跟进人id,
"date": [] ,   //时间,
"trackingContent":'' ,    //跟进内容,
"trackingTypeId": '' ,   //跟进方式,
"contactName":'',
isInvalid:'',
isDeal:'',
"pageNum" : 1,
"pageSize" : 10
};
const defaultForm = {
  cglIds:'',
  remark:'',
  target:''//移入公海，回收站 1 ，称出公海，回收站0
};

export default {
  name: "index",
  data(){
    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      count: 0,
      listLoading: false,
      roles:store.getters.roles ? store.getters.roles : [],
      gridOptions:{
        border: true,
        id: 'followList',
        align:'center',
        rowConfig: {
          keyField: 'trackingId',
          isHover: true
        },
        columnConfig: {
          resizable: true
        },
        customConfig: {
          storage: true,
        },
        toolbarConfig: {
          zoom: true,
          custom: true,
          slots: {
            buttons: 'toolbar_buttons',
          }
        },

        columns: [
          {
            field: 'customerName',
            title: '客户名称',
            width: 150,
            slots: {
              // 使用插槽模板渲染
              default: 'num1_default',
            }
          },
          // {
          //   field: 'contactName',
          //   title: '联系人姓名',
          //   width: 150,
          // },
          {
            field: 'goodsLineName',
            title: '产品线',
            width: 150,
          },
          {
            field: 'developStep',
            title: '开发阶段',
            width: 150,
          },
          {
            field: 'trackingUser',
            title: '跟进人',
            width: 100,
          },
          {
            field: 'trackingTypeName',
            title: '跟进方式',
            width: 100,
          },
          {
            field: 'trackingContent',
            title: '跟进内容',
            showOverflow:true,
            width: 150,
          },
          {
            field: 'isInvalid',
            title: '跟进类型',
            width: 100,
            slots: {
              // 使用插槽模板渲染
              default: 'num2_default',
            }
          },
          {
            field: 'fromBuyReasonStr',
            title: '客户原因',
            width: 150,
          },
          {
            field: 'trackingTime',
            title: '跟进时间',
            width: 150,
          },
          {
            field: 'nextTrackingTime',
            title: '下次跟进时间',
            width: 150,
          },
          {
            field: 'trackingRemark',
            title: '备注',
            width: 150,
            showOverflow:true,
          },
          {
            field: 'customerNewIndustry',
            title: '客户行业',
            width: 100,
          },{
            field: 'cglMonthBuyNum',
            title: '月使用量 ',
            width: 150,
          },
          {
            field: 'cglScale',
            title: '规模 ',
            width: 150,
          },
          {
            field: 'cglOperatingRate',
            title: '开工率 ',
            width: 100,
          },
          {
            field: 'cglCompetitorInfoName',
            title: '对手情况 ',
            width: 100,
          },
          {
            field: 'cglPayMethod',
            title: '付款方式 ',
            width: 100,
          },
          {
            field: 'createTime',
            title: '创建时间 ',
            width: 150,
          },
          {
            field: '',
            title: '操作',
            width: 150,
            fixed:'right',
            slots: {
              // 使用 JSX 渲染
              default: ({ row }) => {
                if(row.cglId && this.listQuery.tab == 'allCustomersPL'){
                  return [
                    <el-button style="margin-right:10px;" type="text" size="small" onClick={ () => this.showEdit(row) }>编辑</el-button>,
                    <el-button style="margin-right:10px;" type="text" size="small" onClick={ () => this.delItem(row) }>删除</el-button>,
                  ]
                } else if(row.cglId && row.isCanUpdate == 1){
                  return [
                    <el-button style="margin-right:10px;" type="text" size="small" onClick={ () => this.showEdit(row) }>编辑</el-button>,
                    <el-button style="margin-right:10px;" type="text" size="small" onClick={ () => this.delItem(row) }>删除</el-button>,
                  ]
                }else if(row.isCanUpdate == 1){
                  return [
                    <el-button style="margin-right:10px;" type="text" size="small" onClick={ () => this.delItem(row) }>删除</el-button>,
                  ]
                }else{
                  return ''
                }
              }
            },
          },
        ],
        data:[],
      },
      querySearchList:[],
      userOptionList:[],
      customerTrackingList:[],
      customerCount:'',
      btnLoading:false
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
    departmentPL(){
      if(this.roles.indexOf("departmentPL") != -1){
        return true
      }else{
        return false
      }
    },
    allCustomersPL(){
      if(this.roles.indexOf("allCustomersPL") != -1){
        return true
      }else{
        return false
      }
    },
    exportfollow(){
      if(this.roles.indexOf("exportfollow") != -1){
        return true
      }else{
        return false
      }
    },
  },
  components : {
    addGj
  },
  created() {
      this.getUserOptionList();
      this.getCustomerSettingList();
      this.getList()
  },

  filters: {

  },
  methods:{
    //下载excle
    downloadExcel(){
      let params = JSON.parse(JSON.stringify(this.listQuery));
      params.isExport = 1;
      delete params.pageSize;
      delete params.pageNum;
      this.btnLoading = true;
      customerNewTrackingList(params).then((res)=>{
        this.btnLoading = false
        require.ensure([], () => {
          const { export_json_to_excel } = require('sheet/Export2Excel');
          const tHeader = res.title;
          const filterVal = res.columns;
          const list = res.list;
          const data = this.formatJson(filterVal, list);
          export_json_to_excel(tHeader, data, res.fileName);
        })
      }).catch(()=>{
        this.btnLoading = false
      })
    },

    //下载表格数据格式化
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    handleSelect(key){
      this.listQuery = JSON.parse(JSON.stringify(defaultListQuery))
      this.listQuery.tab = key;
      this.handleSearchList();
    },

    //编辑跟进
    showEdit(item){
      this.$refs.addGj.showTracking(item,'edit')
    },

    //新增跟进
    showGj(){
      this.$refs.addGj.showTracking('','addMy')
    },

    delItem(item){
      this.$confirm('确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        customerNewDelTracking({trackingId:item.trackingId}).then(()=>{
          this.getList()
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },

    //获取客户配置
    getCustomerSettingList() {
      getCustomerSetting().then((res) => {
        res.forEach((el) => {
          if (el.cdtCode == 'customer_tracking') {
            this.customerTrackingList = el.data;
          }
        });
      })
    },
    toDetail(item){
      let routeData = this.$router.resolve({name:'customerGoodsLineInfo',query:{id:item.customerId}});
      window.open(routeData.href);
    },

    //获取员工下拉选项
    getUserOptionList(){
      getOrderUsersList({status:1}).then((res)=>{
        this.userOptionList = res;
      })
    },
    //客户名称输入匹配
    querySearch(queryString){
      if(queryString && queryString!= '') {
        getCustomerOption({keywords: queryString,tab:this.listQuery.tab == '1' ? 'my' : ''}).then((res) => {
          this.querySearchList = res;
        })
      }
    },
    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getList();
    },

    //获取列表
    getList() {
      this.listLoading = true;
      let listQuery = JSON.parse(JSON.stringify(this.listQuery))
      customerNewTrackingList(listQuery).then(response => {
        this.gridOptions.data = response.list;
        this.count = response.count;
        this.customerCount = response.customerCount;
        this.listLoading = false;
      }).catch(()=>{
        this.listLoading = false;
      });
    },


  },
}
</script>

<style  lang="scss">

.mergeCell .vxe-cell{padding:0;}
.mergeDiv{
  padding-left:10px;
  padding-right:10px;
  border-bottom:1px solid #e8eaec;
  min-height: 36px;
}

.mergeDiv:last-child{
  border-bottom: 0;
}
</style>
